package com.iukcy.hight.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.iukcy.hight.listenner.TClassDataListener;
import com.iukcy.hight.model.TClass;
import com.iukcy.hight.service.ClassService;
import com.iukcy.hight.util.CodeMsg;
import com.iukcy.hight.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <strong>方法描述 ：</strong> <br/>
 * <strong>创建时间：</strong> 2020/9/23 11:47 上午<br/>
 * 
 * @param 
 * @return 
 */
@Controller
@RequestMapping("/excel")
public class ExcelController {
    private final static Logger logger = LoggerFactory.getLogger(ExcelController.class);
    @Autowired
    ClassService classService;

    @RequestMapping("/import")
    public String importPage() {
        return "import";
    }

    /**
     * <strong>方法描述 ：</strong> 导入excel<br/>
     * <strong>创建时间：</strong> 2020/9/22 3:09 下午<br/>
     *
     * @param [classId, userId]
     * @return com.iukcy.hight.util.Result<java.lang.String>
     */
    @RequestMapping("/importExcel")
    @ResponseBody
    public Result<String> importExcel(@RequestParam MultipartFile excel) {
        try {
            EasyExcel.read(excel.getInputStream(), TClass.class, new TClassDataListener(classService)).headRowNumber(2).sheet().doRead();
        } catch (Exception e) {
            return Result.error(CodeMsg.SERVER_ERROR);
        }
        return Result.success("导入成功");
    }

    /**
     * <strong>方法描述 ：</strong> 表格导出<br/>
     * <strong>创建时间：</strong> 2020/9/23 9:24 上午<br/>
     *
     * @param [response]
     * @return com.iukcy.hight.util.Result<java.lang.String>
     */
    @RequestMapping("/export")
    public Result<String> export(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=class-" + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), TClass.class).sheet("sheet0").doWrite(classService.getAll());

        } catch (Exception e) {
            response.reset();
            response.resetBuffer();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                response.getWriter().println(JSON.toJSONString(Result.error(CodeMsg.SERVER_ERROR)));
            } catch (Exception er) {
                e.getStackTrace();
            }

        }
        return null;
    }


}
